package cs.rsa.ts14.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * Helps executing commands in the shell.
 * Currently only supports Windows.
 */
public class ShellHelper {
	/**
	 * Execute commands in the Windows shell and print output to the shell
	 * @param command
	 * @param stream
	 * @return Output from the command
	 */
	public static String execute(String command, PrintStream stream) {
		StringBuilder sb = new StringBuilder();
		String[] commands = new String[] { "cmd", "/c", command };
		try {
			Process proc = new ProcessBuilder(commands).start();
			BufferedReader stdInput = new BufferedReader(new InputStreamReader(
					proc.getInputStream()));

			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					proc.getErrorStream()));

			String s = null;
			while ((s = stdInput.readLine()) != null) {
				sb.append(s);
				sb.append("\n");

				if (stream != null) {
					stream.println(s);
				}
			}

			while ((s = stdError.readLine()) != null) {
				sb.append(s);
				sb.append("\n");
				
				if (stream != null) {
					stream.println(s);
				}
			}
		} catch (IOException e) {
			return e.getMessage();
		}
		return sb.toString();
	}
	
	/**
	 * Execute commands in the Windows shell
	 * @param command
	 * @return Output from the command
	 */
	public static String execute(String command) {
		return execute(command, null);
	}
}
